package com.javasm.mb_store_api_final.config.adminLogin.config;


import com.alibaba.fastjson2.JSON;

import com.javasm.common.R;

import com.javasm.mb_store_api_final.adminLogin.login.admin.AdminAuthenticationProvider;
import com.javasm.mb_store_api_final.adminLogin.login.admin.AdminLoginFilter;
import com.javasm.mb_store_api_final.config.adminLogin.login.phone.PhoneAuthenticationProvider;
import com.javasm.mb_store_api_final.config.adminLogin.login.phone.PhoneLoginFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.filter.CorsFilter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Configuration
//开启security授权注解
@EnableGlobalMethodSecurity(securedEnabled = true,prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    //跨域
    @Resource
    CorsFilter corsFilter;
    //密码加密
    @Bean
    public PasswordEncoder passwordEncoder() {
        //指明算法,代替系统原有的算法
        //加入这行代码之后,密码,必须加密
        return new BCryptPasswordEncoder();
    }

    @Bean
    public PhoneLoginFilter phoneLoginFilter() throws Exception {
        PhoneLoginFilter filter = new PhoneLoginFilter();
        filter.setAuthenticationManager(authenticationManagerBean());
        //登录成功页面
        filter.setAuthenticationSuccessHandler(SecurityConfig::createSuccessJSON);
        //登录失败页面
        filter.setAuthenticationFailureHandler(SecurityConfig::createErrorJSON);
        //因为在PhoneLoginFilter中 已经设置过登录的路径,不再设置
        return filter;
    }

    @Resource
    PhoneAuthenticationProvider phoneAuthenticationProvider;

    @Bean
    public AdminLoginFilter AdminLoginFilter() throws Exception {
        AdminLoginFilter filter = new AdminLoginFilter();
        filter.setAuthenticationManager(authenticationManagerBean());
        //登录成功页面
        filter.setAuthenticationSuccessHandler(SecurityConfig::createSuccessJSON);
        //登录失败页面
        filter.setAuthenticationFailureHandler(SecurityConfig::createErrorJSON);
        //因为在PhoneLoginFilter中 已经设置过登录的路径,不再设置
        return filter;
    }

    @Resource
    com.javasm.mb_store_api_final.adminLogin.login.admin.AdminAuthenticationProvider AdminAuthenticationProvider;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //http未登录不能访问
        //所有的请求,都必须是认证之后才能访问

        http.authorizeRequests()
                //.antMatchers("/dynamic/**").permitAll()
                .antMatchers("/login/**").anonymous()
                .anyRequest()
                .permitAll();

        //在UsernamePasswordAuthenticationFilter过滤器之前,添加一个过滤器corsFilter
        http.addFilterBefore(corsFilter,UsernamePasswordAuthenticationFilter.class);
        //配置JSON格式登录 加过滤器,告诉Security 是哪个类型的过滤器
        //配置 手机号验证码登录
        http.addFilterAt(phoneLoginFilter(), UsernamePasswordAuthenticationFilter.class)
                .authenticationProvider(phoneAuthenticationProvider);
        http.addFilterAt(AdminLoginFilter(), UsernamePasswordAuthenticationFilter.class)
                .authenticationProvider(AdminAuthenticationProvider);
        //自定义 403
        http.exceptionHandling().accessDeniedHandler((request,response,e)->{
            createJSON(response,"没有权限");
        });
        //未登录 返回json
        http.exceptionHandling()
                .authenticationEntryPoint(SecurityConfig::createErrorJSON);

        //退出登录
        http.logout().disable();
        //csrf防跨域伪造 关闭

        http.csrf().disable();
    }

    //放过静态资源

    @Override
    public void configure(WebSecurity web) throws Exception {
        //绕开  security框架,能访问的地址
        web.ignoring().antMatchers("/css/**", "/js/**", "*.html");
    }

    public static void createJSON(HttpServletRequest request,
                                  HttpServletResponse response,
                                  Object o) throws IOException {
        createJSON(response,o);
    }

    private static void createJSON(HttpServletResponse response, Object o) throws IOException {
        //想返回数据,向Response对象中 设置内容
        response.setContentType("application/json;charset=utf-8");
        //向浏览器 写出数据的对象
        PrintWriter writer = response.getWriter();
        //写什么json,内容是什么
        R r = R.ok(o);
        String json = JSON.toJSONString(r);
        writer.write(json);
        writer.flush();
        writer.close();
    }
    public static void createErrorJSON(HttpServletRequest request,
                                       HttpServletResponse response,
                                       AuthenticationException e) throws IOException {
        e.printStackTrace();
        //想返回数据,向Response对象中 设置内容
        response.setContentType("application/json;charset=utf-8");
        //向浏览器 写出数据的对象
        PrintWriter writer = response.getWriter();
        //写什么json,内容是什么
        R r = R.error(e);
        String json = JSON.toJSONString(r);
        writer.write(json);
        writer.flush();
        writer.close();
    }
    public static void createSuccessJSON(HttpServletRequest request,
                                         HttpServletResponse response,
                                         Authentication authentication) throws IOException {
        //想返回数据,向Response对象中 设置内容
        response.setContentType("application/json;charset=utf-8");
        //向浏览器 写出数据的对象
        PrintWriter writer = response.getWriter();
        //写什么json,内容是什么
        R r = R.ok(authentication.getPrincipal());
        String json = JSON.toJSONString(r);
        writer.write(json);
        writer.flush();
        writer.close();
    }
}
